***** READ ALL  and MERGE********
tempfile temp

cd "$path"
//cd C:\DATA\Dropbox\Bank_robberies\Technology\data
cap log close
*log using merge.log, replace
set more off



use "Data/proprietary/agenzia", clear
sort chiave_agenzia year
save, replace

bysort chiave_agenzia year: keep if _n==1
merge chiave_agenzia year using "Data/proprietary/caratteristiche_wide"
tab _m
drop if _m==2 // these are bank branches with no anagrafica data 
drop _m
drop if year==.

keep chiave_agenzia codice_abi confinanti_edificio rischio_contanti numero_dipendenti codice_collocazione year

sort chiave_agenzia year
merge chiave_agenzia year using "Data/proprietary/caratteristiche_wide"
tab _m
drop if _m==2 // these are bank branches with no agenzia data 
drop _m


sort chiave_agenzia year 
merge chiave_agenzia year using "Data/proprietary/guards" //
tab _m
drop if _m==2 // these are guards obs with no agenzia data; _m==1 are banks without guards 
*sort chiave_agenzia year
drop _m
sort chiave_agenzia year
save `temp', replace


use "Data/proprietary/rapine_OSSIF", clear
foreach y of varlist CHIAVE_EVENTO-ESITO{
local ly=lower("`y'")
ren `y' `ly'
}

gen year=substr(data,7,4)
gen month=substr(data,4,2)
destring year month, replace

sort chiave_agenzia year
gen unsuccessful=esito==1
gen attempted=esito!=.
ren importo haul

keep haul unsuccessful attempted year month chiave_agenzia

/*preserve 
collapse haul (sum) unsuccessful attempted, by(chiave_agenzia year month)
merge chiave_agenzia year using temp
tab _m
drop if _m==1 // there are also a few robberies with no matches with agenzia/year
drop _m
save master_spatial_new_month, replace
restore */

collapse haul (sum) unsuccessful attempted, by(chiave_agenzia year)
merge chiave_agenzia year using `temp'
tab _m
drop if _m==1 // there are also a few robberies with no matches with agenzia/year
drop _m
save "Data/proprietary/00 Merged Data", replace
